package com.woniu.carrent.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.woniu.carrent.pojo.TUser;
import com.woniu.carrent.pojo.dto.TUserDto;
import com.woniu.carrent.pojo.vo.TUserVo;
import com.woniu.carrent.service.TUserService;
import com.woniu.carrent.util.RedisUtils;
import com.woniu.carrent.util.ResultMessage;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upuser")
@CrossOrigin
@SaCheckLogin
public class LoginController {
//    验证码前缀
    private static final String REDIS_CODE_PREFIX = "lbw666";
    @Autowired
    private RedisUtils redis;
    @Autowired
    private TUserService tUserService;
    /**
     * 随机生成一个验证码 的图片
     */
    @RequestMapping("getCode")
    public ResultMessage<Map> getCode(String codeId){
        //判断用户是否是第一次访问？生成新的codeId:直接使用
        if(codeId==null||codeId.isEmpty()){
            //生成唯一的key(用糊涂包依赖工具)
            codeId = IdUtil.getSnowflakeNextIdStr();
        }
        //设置验证码图片长、宽、验证码字符数、干扰线宽度
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 30, 1, 10);
        //设置字体样式和大小
        lineCaptcha.setFont(new Font("仿宋", Font.BOLD, 30));
        //获取验证码
        String code = lineCaptcha.getCode().toUpperCase();//转换大写
        //保存验证码到redis中
        redis.set(REDIS_CODE_PREFIX+codeId,code,60);
        System.out.println("验证码:" + code);
        //转为Base64字符串
        String imageBase64 = lineCaptcha.getImageBase64Data();
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("img",imageBase64);
        reqMap.put("codeId",codeId);
        return ResultMessage.success(reqMap);
    }

    /**
     * 登陆接口
     * @param tuserDto
     * @return
     */
    @RequestMapping("/login")
    public ResultMessage login( @RequestBody TUserDto tuserDto) {
        // 判断验证码是否正确
        String CODE = redis.get(REDIS_CODE_PREFIX + tuserDto.getCodeId());
        if (tuserDto.getVerifyCode() == null || tuserDto.getVerifyCode().isEmpty()) {
            return ResultMessage.fail("验证码不存在", 522, tuserDto);
        }

        if (CODE == null) {
            return ResultMessage.fail("验证码已过期", 523, tuserDto);
        }

        if (!CODE.equalsIgnoreCase(tuserDto.getVerifyCode().toUpperCase())) {
            return ResultMessage.fail("验证码错误", 521, tuserDto);
        }

        TUser TUser = new TUser();
        BeanUtils.copyProperties(tuserDto, TUser);
        ResultMessage userMessage = tUserService.login(TUser);
        // 检查返回结果是否是TUser对象
        if (userMessage.getCode() ==200) {
            TUser user = (TUser) userMessage.getData();
            System.out.println(user);
            if (user != null) {
                TUserVo resultUser = new TUserVo();
                //使用sa-token
                BeanUtils.copyProperties(user,resultUser);//拷贝用户信息
                StpUtil.logout(user.getUserid());//删除旧token
                StpUtil.login(user.getUserid(),30*60);
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();//获取token
                resultUser.setTokenInfo(tokenInfo);
                Map<String,Object> reqMap = new HashMap<>();
                reqMap.put("token",resultUser.getTokenInfo().getTokenValue());
                reqMap.put("user",user);
                return ResultMessage.success(reqMap);
            } else {
                return userMessage;
            }
        } else {
            return userMessage;
        }
    }
    /**
     * 注册接口
     */
    @PostMapping("/register")
    public ResultMessage register(@RequestBody TUserDto tuserDto) {

        // 检查用户名是否已存在
        QueryWrapper<TUser> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("phone", tuserDto.getPhone());
        TUser existingUser = tUserService.getOne(checkWrapper);

        if (existingUser != null) {
            return ResultMessage.fail("用户号码已注册", 530, tuserDto);
        }

        // 创建新用户
        TUser newUser = new TUser();
        BeanUtils.copyProperties(tuserDto, newUser);

        // 对密码进行加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(tuserDto.getPassword().getBytes());
        newUser.setPassword(encryptedPassword);

        // 设置默认头像（可选）
        if (newUser.getIcon() == null || newUser.getIcon().isEmpty()) {
            newUser.setIcon("https://esan688.oss-cn-beijing.aliyuncs.com/avatars/%E8%B6%85%E7%AE%A1/1754565535365_%E6%A2%A6%E8%88%9F.jpg");
        }

        // 保存用户
        boolean saved = tUserService.save(newUser);

        if (saved) {
            // 注册成功后可选自动登录
            TUser resTUser = new TUser();
            resTUser.setUsername(newUser.getUsername());
            resTUser.setIcon(newUser.getIcon());
            return ResultMessage.success("注册成功",200 ,resTUser);
        } else {
            return ResultMessage.fail("注册失败，请稍后重试", 531, tuserDto);
        }
    }

}
